package com.example.controller;


import com.example.latch.HazelcastMapLatch;
import com.example.latch.LatchListener;
import com.example.service.HazelcastService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


/*
 * @className: TestHazelcastLatch
 * @author: chentao
 * @date: 2025/2/19 上午9:21
 * @Version: 1.0
 * @description: 测试分布式锁
 */
@RestController
public class TestHazelcastLatch implements InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    private HazelcastMapLatch latch;

    @Resource
    private HazelcastService hazelcastService;

    @Override
    public void destroy() throws Exception {
        this.latch.stop();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.latch = new HazelcastMapLatch(getClass().getName(), hazelcastService, new LatchListener() {
            @Override
            public void isMaster() {
                while (true) {
                    try {
                        logger.warn("我是主节点 ...");
                        Thread.sleep(10000);
                    } catch (Exception e) {
                        logger.warn("业务处理失败: " + e.getMessage());
                    } finally {
                        //资源释放
                    }
                }
            }
        });
        this.latch.start();
    }
}